import UnoCSS from 'unocss/vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Components from 'unplugin-vue-components/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import viteCompression from 'vite-plugin-compression'
import Icons from 'unplugin-icons/vite'
import { FileSystemIconLoader } from 'unplugin-icons/loaders'
import IconsResolver from 'unplugin-icons/resolver' // https://github.com/antfu/unplugin-icons
import cesium from 'vite-plugin-cesium'
import ViteMonacoPlugin from 'vite-plugin-monaco-editor'
import { Languages } from 'vite-plugin-monaco-editor-nls'
import zh_CN from '../../public/main.i18n.json'
import { visualizer } from 'rollup-plugin-visualizer'

/**
 * @description: 设置vite插件配置
 * @param {*} env - 环境变量配置
 * @return {*}
 */
export function createVitePlugins(env) {
  const plugins = [
    vue(),
    vueJsx(),
    cesium(),
    UnoCSS(),
    visualizer({ open: true }),
    // 自动导入 API 依赖
    AutoImport({
      imports: [
        'vue',
        'vue-router',
        'pinia',
        '@vueuse/core',
        {
          'naive-ui': ['useDialog', 'useMessage', 'useNotification', 'useLoadingBar', 'useModal']
        }
      ],
      include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/, /\.md$/]
    }),
    // 自动导入组件库
    Components({
      resolvers: [
        IconsResolver({
          prefix: false,
          customCollections: ['svg-icons']
        }),
        NaiveUiResolver()
      ]
    }),
    ViteMonacoPlugin.default({
      locale: Languages.zh_hans,
      localeData: zh_CN.contents
    }),
    // 自动导入iconify的图标
    Icons({
      defaultStyle: 'display:inline-block',
      compiler: 'vue3',
      customCollections: {
        'svg-icons': FileSystemIconLoader('src/assets/svg-icons', (svg) =>
          svg.replace(/^<svg /, '<svg fill="currentColor" width="1.2em" height="1.2em"')
        )
      }
    })
  ]
  // 压缩设置
  if (env.VITE_BUILD_COMPRESS === 'Y') {
    const { VITE_COMPRESS_TYPE = 'gzip' } = env
    plugins.push(
      viteCompression({
        algorithm: VITE_COMPRESS_TYPE // 压缩算法
      })
    )
  }
  return plugins
}
